<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>数组的累加器</title>
</head>
<body>
    

<script>

    var ary = [1,2,3,4,5];

    ary.reduce((prev,next,index,arr)=>console.log(prev,next,index,arr)); 
    
    /*
     1 2 1  [1, 2, 3, 4, 5]
     undefined 3 2  [1, 2, 3, 4, 5]
     undefined 4 3  [1, 2, 3, 4, 5]
     undefined 5 4  [1, 2, 3, 4, 5]
    */  


    var re = ary.reduce(function(prev,next,index,arr){
        return prev+next;
    }); 

    console.log(re);

    // 常见需求 已知物品的价格和数量的一组数组，求和;

    let products = [
        {price: 30,count: 2},
        {price: 55,count: 3},
        {price: 67,count: 5},
        {price: 22,count: 1},
        {price: 45,count: 6},
        {price: 15,count: 4}
    ];

    //products.unshift(0);

    //let sum = products.reduce((prev,next)=>prev+next.price*next.count);

    let sum = products.reduce((prev,next)=>prev+next.price*next.count,0);// 第二个参数就是设置默认的prev
    
    console.log(sum);
</script>

</body>
</html>